package com.ygxsk.carhome.retrofit;

import java.io.IOException;

import okhttp3.Headers;
import okhttp3.Interceptor;
import okhttp3.MediaType;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.ResponseBody;
import okio.Buffer;

/**
 * OkHttp请求的日志类，主要用于调试网络请求
 */
public class LoggerInterceptor implements Interceptor {

    private static final String TAG = "itchenqi--LoggerInterceptor";

    private boolean showResponse;

    public LoggerInterceptor() {
        this.showResponse = true;
    }

    @Override
    public Response intercept(Chain chain) throws IOException {
        Request request = chain.request();
        logForRequest(request);
        Response response = chain.proceed(request);
        return logForResponse(response);
    }

    private Response logForResponse(Response response) {

        try { // ===> response log
            if (showResponse) {
                Response.Builder builder = response.newBuilder();
                Response clone = builder.build();
                //LogUtils.i(TAG, "url : " + clone.request().url());
                //LogUtils.i(TAG, "code : " + clone.code() + "    message : " + clone.message());
                ResponseBody body = clone.body();
                if (body != null) {
                    MediaType mediaType = body.contentType();
                    if (mediaType != null) {
                        //LogUtils.i(TAG, "responseBody's contentType : " + mediaType.toString());
                        if (isText(mediaType)) {
                            String resp = body.string();
                            //LogUtils.i(TAG, "请求的结果返回: " + resp);

                            //body = ResponseBody.create(mediaType, resp);
                            body = ResponseBody.create(resp, mediaType);
                            return response.newBuilder().body(body).build();
                        } else {
                            //LogUtils.i(TAG, "responseBody's content : " + " maybe [file part] , too large too print , ignored!");
                        }
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return response;
    }

    private void logForRequest(Request request) {
        try {
            if (showResponse) {
                String url = request.url().toString();
                Headers headers = request.headers();

                //LogUtils.i(TAG, "method : " + request.method() + " --> " + "url : " + url);
                if (headers != null && headers.size() > 0) {
                    //LogUtils.i(TAG, "headers : " + headers.toString());
                }
                RequestBody requestBody = request.body();
                if (requestBody != null) {
                    //LogUtils.i(TAG, "请求的参数: " + bodyToString(request));
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private boolean isText(MediaType mediaType) {
        if (mediaType.type() != null && mediaType.type().equals("text")) {
            return true;
        }
        if (mediaType.subtype() != null) {
            if (mediaType.subtype().equals("json") ||
                    mediaType.subtype().equals("xml") ||
                    mediaType.subtype().equals("html") ||
                    mediaType.subtype().equals("webviewhtml")
            )
                return true;
        }
        return false;
    }

    private String bodyToString(final Request request) {
        try {
            final Request copy = request.newBuilder().build();
            final Buffer buffer = new Buffer();
            copy.body().writeTo(buffer);
            return buffer.readUtf8();
        } catch (final IOException e) {
            e.printStackTrace();
            return "something error when show requestBody.";
        }
    }

}